#include "IndexErr.h"

#include <stdarg.h>
#include <string.h>
#include <fan-llvm/core/Core.h>
#include "Str.h"
#include "Type.h"


Type* IndexErr_classType = NULL;
VTable* IndexErr_classVTable = NULL;


/**********************************************
 *
 * Methods and fields
 *
 **********************************************/


/* Void make(Str msg, Err? cause) */
void IndexErr_make_0(IndexErr* self)
{
  IndexErr_make(self, Str_defVal(), NULL);
}


/* Void make(Str msg, Err? cause) */
void IndexErr_make_1(IndexErr* self, Str* msg)
{
  IndexErr_make(self, msg, NULL);
}


/* Void make(Str msg, Err? cause) */
void IndexErr_make(IndexErr* self, Str* msg, Err* cause)
{
  Err_make((Err*)self, msg, cause);
}


/**********************************************
 *
 * Extra methods
 *
 **********************************************/


/* Create a new IndexErr instance and initialize it with IndexErr_make() */
IndexErr* IndexErr_new(Str* msg, Err* cause)
{
  IndexErr* err = (IndexErr*)Obj_allocate(sizeof(IndexErr), IndexErr_classVTable);
  IndexErr_make(err, msg, cause);
  return err;
}


/* Create a new IndexErr instance and initialize it with the message given by the specified format.
 * 'msgFormat' uses the same format as Str_newWithFormat() */
IndexErr* IndexErr_newWithFormattedMsg(const char* msgFormat, ...)
{
  va_list args;
  va_start(args, msgFormat);
  Str* msg = Str_newWithFormatValist(msgFormat, args);
  va_end(args);
  return IndexErr_new(msg, NULL);
}


/* Create the IndexErr instance to throw when the given index is out of bounds */
IndexErr* IndexErr_newWithIndex(Int index)
{
  return IndexErr_newWithFormattedMsg("Index '%i' out of bounds", index);
}


/* Create the IndexErr instance to throw when the given range (e.g. when slicing) is out of bounds */
IndexErr* IndexErr_newWithRange(Range* range)
{
  return IndexErr_newWithFormattedMsg("Range '%r' out of bounds", range);
}


/**********************************************
 *
 * Type-system functions
 *
 **********************************************/


Type* IndexErr_initType(void)
{
  if (IndexErr_classType == NULL)
  {
    Type* baseType = Err_initType();
    VTable* vtable = IndexErr_initVTable();
    Type* type = Type_new("IndexErr", baseType, vtable, sizeof(IndexErr), sizeof(IndexErrVTable));
    Type_registerCtorImplementation(type, "make", IndexErr_make_0, 0);
    Type_registerCtorImplementation(type, "make", IndexErr_make_1, 1);
    Type_registerCtorImplementation(type, "make", IndexErr_make, 2);
    IndexErr_classType = type;
    IndexErr_initStatic();
  }
  return IndexErr_classType;
}


VTable* IndexErr_initVTable(void)
{
  if (IndexErr_classVTable == NULL)
  {
    VTable* vtable = memoryAlloc(sizeof(IndexErrVTable));
    memcpy(vtable, Err_initVTable(), sizeof(ErrVTable));
    IndexErr_classVTable = vtable;
  }
  return IndexErr_classVTable;
}


void IndexErr_initStatic(void)
{
}
